var frontBaseUrl = "http://localhost:5500";
var backBaseUrl = "http://localhost:8080";
var blockId = 0;
var clazzId = 0;
var uid = -1;
var user = null;
var editor;
var nowPage = 1;
var posterInfo;
var post;
var banned = false;



function checkIfUserBanned(id) {
    console.log(blockId)
    console.log("blokidis" + blockId)
    $.post({
        url:'http://localhost:8080/authority/checkUserBanned',
        data:{
            "userId": id,
            "blockId": blockId
        },success: function (msg){
            let ban = msg.data.banList
            if(ban !== undefined && ban !== null &&ban.length !== 0){
                $("#new-post-div").html("<span id='banned-tip'>您已被禁言到" + ban[0].endTime +"====</span>")
            }
        }
    })
}

function loadEditor() {
    window.editor = editormd("editor", {
        width: "100%",
        height: "400px",
        placeholder: "输入回贴内容",
        path: "../../lib/editor.md/lib/",  // Autoload modules mode, codemirror, marked... dependents libs path
        saveHTMLToTextarea: true,
        imageUpload:true,
        imageFormats:["jpg","jpeg","gif","png","bmp","webp"],
        imageUploadURL:"http://localhost:8080/image/uploadPostImage",
    });

}


/**
 * 如果用户没有登录，就禁用用户发帖的权限
 *
 *
 *
 * */
function checkLogin(){
    // console.log("checking login")
    $.post({
        url: 'http://localhost:8080/login/checkLogin',
        async:false,
        method: 'POST',
        crossDomain: true,
        xhrFields: { withCredentials: true },
        success: function (msg) {
            console.log(123444444444)
            let user = msg.data.user;
            console.log(msg)
            //    user是
            if( user === undefined){
                $("#new-post-div").empty();
            }

            if(user !== undefined && user !== null){ console.log("user saved"); window.user = user;}
            // console.log(window.user)
        }, error: function (error) {
            layer.msg("登录信息获取失败~");
            console.log(error)
        }
    })
}

function loadNav(block,post) {
    console.log(block)
    console.log(post)
    let blockName = "<a href='../block/detail.html?id=" + block.id + "'>";
    blockName += block.name;
    blockName += "</a>";
    $("#block-nav").append(blockName);
    $(".bc-nav-now").append(post.title);
}

function loadOneReply(posterInfo, post,) {
//    loadleft
    console.log("post")
    console.log(post);
    let left_card = "<div class='floor-left-card'>";
    left_card += "<div class='username-div'>" + posterInfo.base.username + "</div>";
    left_card += "<div class='user-avatar-div'>"
    left_card += "<img src='../.." + posterInfo.more.avatarUrl + "'/>";
    left_card += "</div>"
    left_card += "<div class='user-signature'>" + posterInfo.more.signature + "</div>";
    left_card += "<div class='post-count-div'>";
    left_card += "<span>发帖数" + posterInfo.base.post_count + "</span>";
    left_card += "</div></div>";
    let right = "<div class='floor-right-content'>";
    right += "<div class='content-top'> 发表于" + post.createTime + "</div>";
    right += "<div class='content-inner' id='md-" + post.id + "'>";
    right += "<textarea style='display:none'></textarea>";
    right += "</div>";
    right += "<div class='content-bottom'>";
    if(user !== null){
    //    登录了
        right += "<input type='button' class='my-button'";
        //是帖子
        if(posterInfo.postId === undefined){
            right +=  "onclick='reportPost(" + post.id + ")'";
        }else {
            right += "onclick='reportReply(" + post.id + ")'";
        }
        right += "value='举报'/>";
    }
    if(user !== null && posterInfo.base.id === user.base.id ) {
        console.log("added")
        right += "<input type='button' class='my-button' ";
        if(post.postId === undefined){
            right+= "onclick='deletePost(" + post.id + ")'";
        }else {
            right += "onclick='deleteReply(" + post.id + ")'";
        }
        right+= " value='删除'/>";
    }
    right += "</div>";//contentbottom
    right += "</div>";
    let floorItem = "<div class='floor-item'>";
    floorItem += left_card;
    floorItem += right;
    floorItem += "</div>";
    $("#content").append(floorItem);
    $("#md-" + post.id+" textarea").text(post.content);
    editormd.markdownToHTML("md-" + post.id);
}

function loadPost(post,posterInfo,pageList) {
    console.log(123);
    console.log(post);
    console.log(posterInfo)
    console.log(pageList)
    window.post = post;
    window.posterInfo = posterInfo;
    //loadheader
    $("#left-nav").append(post.replyCount);
    $("#title").text(post.title);
    console.log(window.banned)
    if(banned){
        $("#title").html(post.title + "<span class='layui-badge'>该贴已封禁，只有您可以查看</span>")
    }
    if(nowPage !== 1){
        return;
    }
    loadOneReply(posterInfo,post)
}

function loadReplys(replyList) {
    $(replyList).each(function (i,e){
        loadOneReply(e.user,e.reply);
    })
}

function checkBannedPost() {
    let banned = (post.state & 1) === 1;
    console.log("bannnnd")
    if(banned){
        console.log("tiezibeifengle")
        if(user.base.id === post.authorId){

            //是他发的，就可以自己看
            window.banned = true;
            return;
        }
        layer.msg("该贴已被封禁，3秒后返回上一级");
        $("#main-div").empty();
        window.setTimeout(function (){
            window.history.back();
        },3000);
    }
}

function loadData(){
    loadEditor();
    $.post({
        url: backBaseUrl + "/post/init",
        type:"post",
        data:{
            postId:getQueryVariable("id")
        },
        success:function (msg){
            console.log(msg)
            blockId = msg.data.block.id;
            loadNav(msg.data.block,msg.data.post);
            attachPager(msg.data.pageList,1);
            checkLogin();
            window.post = msg.data.post;
            checkBannedPost();
            loadPost(msg.data.post,msg.data.posterInfo,msg.data.pageList);
            loadReplys(msg.data.replyList);
            console.log("哇"+user.base.id)
            checkIfUserBanned(user.base.id)
        },error:function (error){
            layer.msg("帖子信息加载失败,可能已经被删除了,将在3秒后跳转回上一页");
            $("#main-div").empty();
            window.setTimeout(function (){
                window.history.back();
            },3000);
        }
    });
}



function attachPager(pageList, num) {
    $(".page-list").html("");
    maxPage = parseInt(pageList[pageList.length - 1]);
    $(pageList).each(function (i, e) {
        let str = "<div class="
        if (e === num.toString()) {
            str += "'my-button-now'";
        } else {
            str += "'my-button'";
        }
        if (e !== '...') {
            str += "onclick='loadPage(" + e + ")'"
        }
        str += "/>" + e + "</div>";
        $(".page-list").append(str);
    })
}

function lastPage() {
    let tPage = $(".my-button-now").text();
    console.log(tPage)
    let nowPage = parseInt(tPage);
    if (nowPage <= 1) {
        // layer.msg("没有了");
        return;
    }
    loadPage(nowPage - 1);
}

function nextPage() {

    let tPage = $(".my-button-now").text();
    console.log(tPage)
    let nowPage = parseInt(tPage);
    if (nowPage >= maxPage) {
        // layer.msg("没有了");
        console.log("没有了 ")
        return;
    }
    loadPage(nowPage + 1);
}

function jumpToPage() {
    let tPage = $("#jump-input").val();
    console.log(tPage);
    let page = parseInt(tPage);
    console.log(typeof (page))
    console.log(page)
    if (page < 1 || page > maxPage || isNaN(page)) {
        return;
    }
    loadPage(page);
}

function loadPage(page){
    $.ajax({
        url: backBaseUrl + "/postReply/getPostPage",
        type:"post",
        data:{
            "postId":post.id,
            "curPage":page,
            "numPerPage":10
        },
        success: function (msg){
            console.log(msg)
            $("#content").empty();
            if(page === 1){
                loadOneReply(window.posterInfo,window.post);
            }
            $(msg.data.replyList).each(function (i,e){
                loadOneReply(e.user,e.reply);
            })
            attachPager(msg.data.pageList,page);
        }
    })
}

function appendNextPage(){
    let tPage = $(".my-button-now").text();
    console.log(tPage)
    let nowPage = parseInt(tPage);
    if (nowPage >= maxPage) {
        // layer.msg("没有了");
        console.log("没有了 ")
        return;
    }
    loadPage(tPage)
}

function checkPostTitleLen(){
    let title = $("#new-post-title");
    let maxLen = 80;
    if(title.val().length > maxLen){
        title.val(title.val().substring(0,maxLen))
    }
    $("#title-tip").text("还能输入" + (maxLen - title.val().length ) + '字');
}

function sendReply(){
    //获取所有信息
//    存入对象，并把对象发送给服务器
    let post_btn = $("#post-btn");

    let content = window.editor.getMarkdown();
    console.log(content.length)
    if(content.length === 0){
        layer.msg("内容不能为空")
    }
    if(user == null){
        layer.msg("您还未登录！")
        return;
    }
    if(post === null){
        layer.msg("数据获取失败！请刷新重试");
        return;
    }

    post_btn.attr("disabled",true);
    post_btn.text("回复中..");
    $.post({
        url:'http://localhost:8080/postReply/replyOne',
        crossDomain: true,
        xhrFields: { withCredentials: true },
        data:{
            "userId": user.base.id,
            "postId": post.id,
            "content":content
        },success: function (msg){
            //0： 发帖成功
            if(msg.code === 0){
                layer.msg(msg.msg)
                window.location.reload();
            }else if(msg.code === -1){
                layer.msg(msg.msg);
                post_btn.css("disable",false);
                post_btn.text("回复");
            }
        },error:function (error){
            layer.confirm("遇到了一些问题T-T，请你重试，报错信息已经打印到控制台")
            post_btn.css("disable",false);
            post_btn.text("回复");
            console.log(error);
        }
    });
}


function deleteReply(replyId){
    layer.confirm("确定要删除这个回复吗？",{
        btn: ['确定','关闭']
    },function (){
        $.post({
            url: 'http://localhost:8080/postReply/deleteById',
            async:false,
            method: 'POST',
            crossDomain: true,
            xhrFields: { withCredentials: true },
            data:{
                id: replyId,
                userId:user.base.id
            },
            success: function (msg) {
                layer.msg("删除成功");
                window.location.reload()
            },error: function (error){
                layer.msg("删除失败");
                window.location.reload()
            }
        })

    });
}
function deletePost(postId){
    layer.confirm("确定要删除这个帖子吗？",{
        btn: ['确定','关闭']
    },function (){
        $.post({
            url: 'http://localhost:8080/post/deleteById',
            async:false,
            method: 'POST',
            crossDomain: true,
            xhrFields: { withCredentials: true },
            data:{
                id: postId,
                userId:user.base.id
            },
            success: function (msg) {
                layer.msg("删除成功");
                window.location.href='../block/detail.html?id=' + blockId;
            },error: function (error){
                layer.msg("删除失败");
                window.location.reload()
            }
        })
    });
}

function deleteNotice(noticeId){
    $.post({
        url: 'http://localhost:8080/notice/deleteById',
        async:false,
        method: 'POST',
        crossDomain: true,
        xhrFields: { withCredentials: true },
        data:{
            id: noticeId
        },
        success: function (msg) {
            layer.msg("删除成功");

        },error: function (error){
            layer.msg("删除失败");
        }
    });
    window.location.reload()

}

function reportPost(postId){
    layer.open({
        type:2,
        title: '举报',
        shadeClose: true,
        shade: 0.8,
        area:['420px', '240px'],
        content:'../report/userAddReport.html?postId='+postId
    });

}